package com.heaven1949.tmall.common.web.controller;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heaven1949.tmall.common.core.dto.ApiResult;
import com.heaven1949.tmall.common.core.dto.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;

/**
 * BaseContorller
 *
 * @author zhangjian
 */
public class BaseController {

    private static final String PAGE_NUM = "pageNum";
    private static final String PAGE_SIZE = "pageSize";
    private static final String SEARCH_COUNT = "searchCount";
    private static final Integer DEFAULT_LIMIT = 10;
    private static final Integer DEFAULT_NUM = 1;
    private static final Integer MAX_LIMIT = 100;
    @Autowired
    protected HttpServletRequest request;

    /**
     * 获取分页对象
     *
     * @return
     */
    protected <T> Page<T> getPage() {
        // 页数
        Integer cursor = Convert.toInt(request.getParameter(PAGE_NUM), 1);
        // 分页大小
        Integer limit = Convert.toInt(request.getParameter(PAGE_SIZE), DEFAULT_LIMIT);
        // 是否查询分页
        Boolean searchCount = Convert.toBool(request.getParameter(SEARCH_COUNT), true);
        limit = limit > MAX_LIMIT ? MAX_LIMIT : limit;
        Page<T> page = new Page<>(cursor, limit, searchCount);
        return page;
    }

    /**
     * success
     *
     * @return
     */
    public <T> ApiResult<T> success() {
        return success(null);
    }

    /**
     * success
     *
     * @param object
     * @return
     */
    public <T> ApiResult<T> success(T object) {
        return ApiResult.success(object);
    }

    /**
     * failed
     *
     * @param code
     * @return
     */
    public <T> ApiResult<T> failed(ResultCode code) {
        return ApiResult.failed(code);
    }

    /**
     * failed
     *
     * @return
     */
    public <T> ApiResult<T> failed() {
        return ApiResult.failed();
    }

}